package com.hejia.bulbul.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;
import com.hejia.alauda.entity.CreditOperation;
import com.hejia.alauda.entity.CreditOperation.Operation;
import com.hejia.alauda.entity.User;
import com.hejia.alauda.entity.example.CreditOperationExample;
import com.hejia.alauda.service.CreditService;
import com.hejia.alauda.service.UserService;
import com.hejia.alauda.utils.Pager;
import com.hejia.bulbul.entity.DataTablesReturnObject;
import com.hejia.bulbul.entity.JSONParam;

@Controller
@RequestMapping("creditoperation")
public class CreditOperationController extends BaseController {
	
	private static final Log Logger = LogFactory.getLog(CreditOperationController.class);

	@Resource
	private CreditService creditService;

	@Resource
	private UserService userService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String creditOperationList(Pager<CreditOperation> pager,
			ModelMap model) {
		Pager<CreditOperation> creditOperation = creditService
				.findManualCredit(pager);
		model.put("creditOperation", creditOperation);
		return "/creditmanage/creditoperation_list";
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String creditOperationAdd(ModelMap model) {
		return "/creditmanage/creditoperation_input";
	}

	/**
	 *
	 * @param product
	 * @param protocolIds
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String creditOperationAdd(ModelMap model,
			RedirectAttributes redirectAttributes, HttpServletRequest request) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> items = upload.parseRequest(request);
			String description = null;
			Operation operation = CreditOperation.Operation.MANUAL;
			Integer creditChanges = 0;
			String mobiles = null;
			InputStream is = null;
			int success = 0;
			for (FileItem item : items) {
				if (item.isFormField()) {
					if ("description".equals(item.getFieldName())) {
						description = item.getString("utf-8");
					} else if ("creditChanges".equals(item.getFieldName())) {
						creditChanges = Integer.parseInt(item
								.getString("utf-8"));
					} else if ("mobiles".equals(item.getFieldName())) {
						mobiles = item.getString("utf-8");
					}
				} else {
					is = item.getInputStream();
				}
			}
			BufferedReader dr = new BufferedReader(new InputStreamReader(is));
			String mobile = "";
			while (mobile != null) {
				mobile = dr.readLine();
				if (mobile == null) {
					break;
				}
				System.out.println(mobile);
				User user = userService.findUserByMobile(mobile);
				if (user != null&&!"".equals(user.getMobile())) {
					if (creditService.addCreditOperation(creditChanges, user,
							operation, description)) {
						success++;
					}
				}
			}
			dr.close();
			is.close();
			
			Logger.debug(String.format("手机号：%s", mobiles));
			if (mobiles != null) {
				String[] arrMobile = mobiles.split(",");
				for (int i = 0; arrMobile != null && i < arrMobile.length; i++) {
					User user = userService.findUserByMobile(arrMobile[i]);
					Logger.debug(String.format("用户是否为空：%s", user == null));
					if (user != null&&!"".equals(user.getMobile())) {
						Logger.debug(String.format("用户：%s", JSONObject.toJSONString(user)));
						if (creditService.addCreditOperation(creditChanges,
								user, operation, description)) {
							success++;
						}
					}
				}
			}
			redirectAttributes.addFlashAttribute("status", STATUS_SUCCESS);
			redirectAttributes.addFlashAttribute("msg", success + "条积分添加成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "redirect:/creditoperation/list";
	}

	/**
	 * 以ajax格式返回列表请求
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "creditAsAjax", method = RequestMethod.POST)
	@ResponseBody
	public DataTablesReturnObject<CreditOperation> creditAsAjax(
			@RequestBody JSONParam[] params) {
		HashMap<String, String> paramMap = JSONParam.convertToMap(params);

		// 分页信息
		Pager<CreditOperation> pager = new Pager<CreditOperation>();
		int start = Integer.parseInt(paramMap.get("iDisplayStart"));
		int length = Integer.parseInt(paramMap.get("iDisplayLength"));
		pager.setPageSize(length);
		pager.setPageNumber(start / length + 1);

		// 查询条件
		CreditOperationExample exp = new CreditOperationExample();

		String sSearch = paramMap.get("sSearch");
		if (StringUtils.isNotEmpty(sSearch)) {
			exp.appendCriterion("user_id like  ", "%" + sSearch + "%");
		}
		// 排序
		int iSortingCols = Integer.parseInt(paramMap.get("iSortingCols"));
		for (int i = 0; i < iSortingCols; i++) {
			String iSortCol = paramMap.get("iSortCol_" + i);
			String mDataProp = paramMap.get("mDataProp_" + iSortCol);
			String sSortDir = paramMap.get("sSortDir_" + i);
			if (i > 0) {
				exp.setOrderByClause(exp.getOrderByClause() + ",");
				exp.setOrderByClause(exp.getOrderByClause() + mDataProp + " "
						+ sSortDir);
			} else {
				exp.setOrderByClause(mDataProp + " " + sSortDir);
			}
		}

		pager = creditService.findManualCredit(pager, exp);

		DataTablesReturnObject<CreditOperation> dtr = new DataTablesReturnObject<CreditOperation>(
				pager.getTotalCount(), paramMap.get("sEcho"), pager.getList());
		return dtr;
	}

}
